package com.ycrlkj.android.modulespublic.common.net.exception;

import android.net.ParseException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.gson.JsonParseException;
import com.ycrlkj.android.modulesbase.libbase.utils.Logger;
import com.ycrlkj.android.modulespublic.common.net.response.MResponseCode;
import org.json.JSONException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public class ApiException extends Exception {

    private Integer code;
    private String message;

    public ApiException(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    public static ApiException exception2ApiException(Throwable e) {

        ApiException ex;

        if (e instanceof ApiException) {
            //如果抓到的错误是ApiException类型, 则强转为ApiException
            ex = (ApiException) e;
        } else if (e instanceof ConnectException || e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
            ex = new ApiException(MResponseCode.ERROR_500.getCode(), MResponseCode.ERROR_500.getMessage());
            Logger.e("ApiException.exception2ApiException 网络错误, 错误打印开始:");
            e.printStackTrace();
            Logger.e("错误打印结束");
        } else if (e instanceof JsonParseException || e instanceof JSONException || e instanceof ParseException) {
            Logger.e("ApiException.exception2ApiException json转换错误, 错误打印开始:");
            e.printStackTrace();
            Logger.e("错误打印结束");
            ex = new ApiException(MResponseCode.ERROR_DATA_PARSE.getCode(), MResponseCode.ERROR_DATA_PARSE.getMessage());
        } else {
            Logger.e("ApiException.exception2ApiException 未知类型错误, 错误打印开始:");
            e.printStackTrace();
            Logger.e("错误打印结束");
            ex = new ApiException(MResponseCode.ERROR_UNKNOWN.getCode(), MResponseCode.ERROR_UNKNOWN.getMessage());
        }

        return ex;

    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    @Nullable
    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @NonNull
    @Override
    public String toString(){
        return "ApiException{ code: " + code + ", message: " + message + " }";
    }
}
